<template>
  <div class="container">
    <div class="input-container">
      <span class="police1">报警编号</span>
      <el-input
        v-model="input"
        placeholder="请输入内容"
        size="middle"
        class="input-box"
      ></el-input>
      <el-button
        size="middle"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
        class="search-btn"
        >搜索</el-button
      >
      <el-button
        size="middle"
        type="default"
        icon="el-icon-refresh"
        @click="handleReset"
        class="reset-btn"
        >重置</el-button
      >
    </div>
    <div class="option">
      <el-button
        size="middle"
        type="primary"
        icon="el-icon-plus"
        @click="adddialogVisible = true"
        class="add-btn"
        >增加</el-button
      >
      <el-button
        size="middle"
        icon="el-icon-edit"
        @click="handleEdit"
        class="edit-btn"
        >修改</el-button
      >
      
    </div>
    <div class="table-container">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="id"
          label="报警编号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="policeType"
          label="报警类型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="policeLevel"
          label="报警级别"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="machine"
          label="报警所属机型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="modelName"
          label="所属机型名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="报警详细描述"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contact"
          label="报警联系人"
          width="120"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="增加报警"
      :visible.sync="adddialogVisible"
      width="30%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="报警编号" prop="id">
          <el-input v-model="formData.id"></el-input>
        </el-form-item>
        <el-form-item label="报警类型" prop="policeType">
          <el-input v-model="formData.policeType"></el-input>
        </el-form-item>
        <el-form-item label="报警级别" prop="policeLevel">
          <el-select v-model="formData.policeLevel" placeholder="请选择">
            <el-option label="一般" value="一般"></el-option>
            <el-option label="重要" value="重要"></el-option>
            <el-option label="紧急" value="紧急"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警所属机型" prop="machine">
          <el-input v-model="formData.machine"></el-input>
        </el-form-item>
        <el-form-item label="所属机型名称" prop="modelName">
          <el-input v-model="formData.modelName"></el-input>
        </el-form-item>
        <el-form-item label="报警详细描述" prop="description">
          <el-input v-model="formData.description"></el-input>
        </el-form-item>
        <el-form-item label="报警联系人" prop="contact">
          <el-input v-model="formData.contact"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="编辑报警"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="form"
        :model="selectedRow"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="报警编号" prop="id">
          <el-input v-model="selectedRow.id"></el-input>
        </el-form-item>
        <el-form-item label="报警类型" prop="policeType">
          <el-input v-model="selectedRow.policeType"></el-input>
        </el-form-item>
        <el-form-item label="报警级别" prop="policeLevel">
          <el-select v-model="selectedRow.policeLevel" placeholder="请选择">
            <el-option label="一般" value="一般"></el-option>
            <el-option label="重要" value="重要"></el-option>
            <el-option label="紧急" value="紧急"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警所属机型" prop="machine">
          <el-input v-model="selectedRow.machine"></el-input>
        </el-form-item>
        <el-form-item label="所属机型名称" prop="modelName">
          <el-input v-model="selectedRow.modelName"></el-input>
        </el-form-item>
        <el-form-item label="报警详细描述" prop="description">
          <el-input v-model="selectedRow.description"></el-input>
        </el-form-item>
        <el-form-item label="报警联系人" prop="contact">
          <el-input v-model="selectedRow.contact"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </div>
    </el-dialog>

    <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="pageNum"
    :page-sizes="[5,10,15, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total">
  </el-pagination>
  </div>
</template>

<script>
import Axios from "axios";
export default {
  data() {
    return {
      input: "",
      tableData: [],
      selectedRow: null,
      cunchushu1: [],
      selectedNames1: [], // 存放选中行的 name 变量的全局数组
      multipleSelection: [],
      adddialogVisible: false,
      dialogVisible: false,
      pageNum: 1,
      pageSize: 10,
      total:400,
      formData: {
        id: "",
        policeType: "",
        policeLevel: "",
        machine: "",
        modelName: "",
        description: "",
        contact: "",
      },
      selectedRow: {
        id: "",
        policeType: "",
        policeLevel: "",
        machine: "",
        modelName: "",
        description: "",
        contact: "",
      },
      formRules: {
        id: [
          { required: true, message: "请输入报警编号", trigger: "blur" },
        ],
        policeType: [
          { required: true, message: "请输入报警类型", trigger: "blur" },
        ],
        policeLevel: [
          { required: true, message: "请选择报警级别", trigger: "change" },
        ],
        machine: [
          { required: true, message: "请输入报警所属机型", trigger: "blur" },
        ],
        modelName: [
          { required: true, message: "请输入所属机型名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入报警详细描述", trigger: "blur" },
        ],
        contact: [
          { required: true, message: "请输入报警联系人", trigger: "blur" },
        ],
      },
    };
  },
  created(){
    Axios.get("http://localhost:8080/example/alert")
      .then((res) => {
        console.log(res);
        this.tableData = res.data.data;
        this.total = this.tableData.length;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  mounted() {
    this.page();
  },
  methods: {
    handleCurrentChange(pageNum){
      this.pageNum = pageNum;
      this.page();
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize;
      this.page();
    },
    page(){
      Axios.get(`http://localhost:8080/example/alert/page?pageNum=${this.pageNum}&pageSize=${this.pageSize}`)
      .then((res) => {
        console.log(res);
        this.tableData = res.data.data;
        // this.total = this.tableData.length;
      })
      .catch((err) => {
        console.log(err);
      });
    },
    handleReset(){
      this.pageNum = 1;
      this.pageSize = 10;
      // `http://localhost:8080/example/alert?pageNum=${pageNum}&pageSize=${pageSize}`
      this.input = ''
      this.page();
      
    },
    handleSearch() {
  if (!this.input) {
    this.$message.warning("请输入报警编号");
    return;
  }
  Axios.get(`http://localhost:8080/example/alert/search/${this.input}`)
  .then(response => {
    if (response.data.length === 0) {
      this.$message.warning("没有搜索到相关信息");
      return;
    }
    this.tableData = [response.data.data];
  })
  .catch(error => {
    console.log(error);
  });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
    this.multipleSelection = val,
    this.selectedNames1=this.multipleSelection,
    console.log(this.selectedNames1)
    },
    handleEdit(index, row) {
     // 将选中行的数据复制到临时编辑数据中
     this.selectedRow = Object.assign({}, row);
    this.dialogVisible = true;
  },
    handleDelete(index, row) {
      this.$confirm('确定删除该报警记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 从表格中删除该行数据
        this.tableData.splice(index, 1);
        // 发送DELETE请求将该行数据从数据库中删除
        Axios.delete(`http://localhost:8080/example/alert/delete/${row.id}`).then(response => {
          console.log(response.data);
        }).catch(error => {
          console.error(error);
        });
      }).catch(() => {
        // 取消删除操作
      });
    },
    handleDialogClose(done) {
      if (this.dialogVisible) {
        this.$confirm("确认关闭？")
          .then(() => {
            done();
          })
          .catch(() => {});
      } else {
        done();
      }
    },
    handleAddSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          Axios.post("http://localhost:8080/example/alert/add", this.formData)
            .then((res) => {
              console.log(res.data);
              this.tableData.push(this.formData);
              this.dialogVisible = false;
              this.$message({
                message: "提交成功",
                type: "success",
              });
              this.formData = {};
            })
            .catch((error) => {
              console.log(error);
              this.$message({
                message: "提交失败，请检查输入",
                type: "warning",
              });
            });
        } else {
          this.$message({
            message: "提交失败，请检查输入",
            type: "warning",
          });
        }
      });
    },
    handleDelete4() {
      for (let i = 0; i < this.selectedNames1.length; i++) {
        this.cunchushu1.push(this.selectedNames1[i].id);
      } 

      // 确认是否删除
      this.$confirm('确定删除该报警记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for(let i = 0; i<this.cunchushu1.length; i++)
        {
          
              Axios.delete(`http://localhost:8080/example/alert/delete/${this.cunchushu1[i]}`).then(response => {
              console.log(response.data);
            }).catch(error => {
              console.error(error);
            });
        }
        // 遍历表格数据，找到所有在 this.cunchushu1 列表中的行的索引
        const indexesToDelete = [];
        for (let i = 0; i < this.tableData.length; i++) {
          const rowData = this.tableData[i];
          if (this.cunchushu1.includes(rowData.id)) {
            indexesToDelete.push(i);
          }
        }
        // 从表格数据中删除这些行
        for (let i = indexesToDelete.length - 1; i >= 0; i--) {
          this.tableData.splice(indexesToDelete[i], 1);
        }
      }).catch(() => {
        // 取消删除操作
        this.$message({
          message: '已取消删除操作',
          type: 'info'
        });
      });
    },

  
handleEditSubmit() {
    // 表单数据校验
    this.$refs.form.validate((valid) => {
      if (valid) {
        // 发送编辑数据到后端更新数据
        Axios.post(
          `http://localhost:8080/example/alert/update`,
          this.selectedRow
        )
          .then((res) => {
            console.log(res.data);
            // 更新表格数据
            const index = this.tableData.findIndex(
              (item) => item.id === this.selectedRow.id
            );
            if (index !== -1) {
              this.tableData.splice(index, 1, this.selectedRow);
            }
            // 关闭编辑对话框
            this.dialogVisible = false;
            this.$message({
              message: "修改成功",
              type: "success",
            });
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: "修改失败，请检查输入",
              type: "warning",
            });
          });
      } else {
        this.$message({
          message: "修改失败，请检查输入",
          type: "warning",
        });
      }
    });
  },
  
  
},
};
</script>

<style scoped>
.container {
  margin-top: 30px;
}
.police1 {
  margin-right: 20px;
}
.input-container {
  align-items: center;
  margin-bottom: 10px;
  margin-left: 20px;
  display: inline-block;
}

.input-box {
  width: 300px;
  margin-right: 10px;
}

.search-btn {
  margin-left: 10px;
}

.table-container {
  position: relative;
  width: 100%;
}
.option {
  margin-left: 20px;
}
</style>